<script setup lang="ts">
import { ref, defineEmits, onMounted } from 'vue';
import { showToast } from 'vant';
import { addUser, getUserList as getAddedUserList } from '@/api/classroom'; // 课程相关接口
import { getUserList } from '@/api/user'; // 所有系统用户

const props = defineProps<{
  courseId: string;
  show: boolean;
}>();

const emits = defineEmits(['update:show', 'refreshStudentList']);

const userList = ref<any[]>([]);
const selectedIds = ref<string[]>([]);
const addedStudentIds = ref<string[]>([]);
const isLoading = ref(false);

const onClose = () => {
  emits('update:show', false);
};

const onConfirmAdd = async () => {
  if (selectedIds.value.length === 0) {
    showToast('请选择要添加的学生');
    return;
  }
  isLoading.value = true;
  try {
    for (const id of selectedIds.value) {
      await addUser(props.courseId, id, 2); // type=2 表示学生
    }
    showToast('添加成功');
    emits('refreshStudentList');
    onClose();
  } catch (error) {
    console.error('添加失败', error);
    showToast('添加失败');
  } finally {
    isLoading.value = false;
  }
};

// 初始化获取所有用户 + 已添加学生
onMounted(async () => {
  const resAll = await getUserList();
  const resAdded = await getAddedUserList(props.courseId, 2); // type=2 表示学生

  if (resAll.code === 200) {
    userList.value = resAll.data || [];
  } else {
    showToast('获取学生列表失败');
  }

  if (resAdded.code === 200) {
    addedStudentIds.value = (resAdded.data || []).map((u: any) => u.id);
  }
});
</script>


<template>
  <van-popup v-model:show="props.show" position="bottom" round>
    <div style="padding: 16px; position: relative;">
      <van-icon
        name="cross"
        size="24"
        color="#999"
        style="position: absolute; right: 10px; top: 10px; z-index: 10"
        @click="onClose"
      />
      <div style="margin-bottom: 10px; font-weight: bold; text-align: center;">
        选择要添加的学生
      </div>

      <van-checkbox-group v-model="selectedIds">
        <van-cell-group>
          <van-cell
            v-for="user in userList"
            :key="user.id"
            :title="user.nickname"
          >
            <template #right-icon>
              <van-checkbox
                :name="user.id"
                :disabled="addedStudentIds.includes(user.id)"
              />
            </template>
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>

      <van-button
        type="primary"
        block
        style="margin-top: 20px"
        :loading="isLoading"
        @click="onConfirmAdd"
      >
        确认添加
      </van-button>
    </div>
  </van-popup>
</template>

